import {defineStore} from 'pinia'
import {ref} from 'vue'
import {defaultWidgets} from "@/stores/default-data.ts";

interface Widget {
    id: string
    component: string
    width: number
    height: number
    title: string
    show: boolean
    parent_id: string
    url: string
    props?: Record<string, any>
}

/**
 * 这里只应该包括对持久化数据的操作,不应该调用接口或者夹杂其他业务
 * !!!!!
 */
export const useWidgetStore = defineStore('widget', () => {
    const widgets = ref<Widget[]>([
        ...defaultWidgets
    ])
    const fixedWidgets: Widget[] = [
        {
            component: 'setting',
            height: 1,
            width: 1,
            id: '0114ae7c-fe56-1e2e-bcf8-3372d23a1bd8',
            parent_id: '-1',
            show: true,
            title: '系统设置',
            url: '',
            props: {}
        },
        {
            component: 'add',
            id: Date.now().toString(),
            width: 1,
            url: '',
            height: 1,
            title: '添加',
            show: true,
            parent_id: '-1',
            props: {}
        }
    ]
    const widgetTags = ref([] as string[])
    const widgetOrders = ref([] as string[])

    // getters

    // actions
    function addWidget(widget: Widget) {
        widgets.value.push(widget)
    }

    function deleteWidgetById(id: string) {
        const index = widgets.value.findIndex(w => w.id === id)
        if (index !== -1) widgets.value.splice(index, 1)
    }

    /**
     * 设置widgets,并完善标签
     * @param payload
     */
    function setWidgets(payload: Widget[]) {
        widgets.value = [...payload, ...fixedWidgets]

        // 填充标签
        payload
            .filter((w: Widget) => w.component === 'site' && w.props?.tags)
            .forEach((w: Widget) => {
                w.props?.tags?.split(',').forEach((tag: string) => {
                    if (!widgetTags.value.includes(tag)) {
                        widgetTags.value.push(tag)
                    }
                })
            })
    }

    function editWidget(payload: Widget) {
        const index = widgets.value.findIndex(w => w.id === payload.id)
        if (payload.props?.tags) {
            payload.props.tags.split(',').forEach((t: string) => {
                if (!widgetTags.value.includes(t)) {
                    widgetTags.value.push(t)
                }
            })
        }
        if (index !== -1) {
            widgets.value.splice(index, 1, payload)
        } else {
            console.warn('更新失败,未找到对应组件')
        }
    }

    function clearWidgets() {
        widgets.value = []
    }

    function setWidgetOrders(orders: string[]) {
        widgetOrders.value = orders
    }

    function swapWidgetOrder({from, to}: { from: number; to: number }) {
        const moved = widgetOrders.value.splice(from, 1)
        widgetOrders.value.splice(to, 0, moved[0])
    }

    function setAllWidgets(widgets: Widget[]) {
        if (widgets.length > 0) {
            if (widgetOrders.value.length === 0) {
                setWidgetOrders(widgets.filter(w => w.show).map(w => w.id))
            }
            setWidgets(widgets)
        }
    }

    function reset() {
        clearWidgets()
        setWidgetOrders([])
        widgetTags.value = []
    }


    return {
        widgets,
        addWidget,
        deleteWidgetById,
        setWidgets,
        editWidget,
        clearWidgets,
        setWidgetOrders,
        swapWidgetOrder,
        setAllWidgets,
        reset
    }
}, {
    // 持久化
    persist: {
        key: 'widget',
        storage: localStorage
    },
})
